import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useTokenStore = defineStore('mytoken', () => {
  // 初始化时从 localStorage 读取
  const tokenJson = ref(window.localStorage.getItem("TokenInfo") || "")

  const token = computed(() => {
    try {
      if (!tokenJson.value) return {}
      return JSON.parse(tokenJson.value)
    } catch (err) {
      window.localStorage.setItem("TokenInfo", "")
      return {}
    }
  })

  function saveToken(data) {
    const str = typeof data === 'string' ? data : JSON.stringify(data)
    tokenJson.value = str
    window.localStorage.setItem("TokenInfo", str)
  }

  return { token, saveToken }
})